﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

#endregion


namespace ESF.General
{
	internal sealed class Logger : IDisposable
	{
		private delegate void WriteMessage(string message);		
		private readonly object Locker = new object();
		private readonly TextWriter Writer;
		private bool Disposed;

		public Logger (string pCategory)
		{
			Writer = ESF.General.Log.GetLogWriter(pCategory);
		}

		~Logger()
		{
			Dispose (false);
		}

		public void Log (string message)
		{
			WriteMessage action = MessageWriter;
			action.BeginInvoke (message, MessageWriteComplete, action);
		}

		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		private static void MessageWriteComplete(IAsyncResult iar)
		{
			((WriteMessage)iar.AsyncState).EndInvoke(iar);
		}

		private void Dispose(bool disposing)
		{
			lock (Locker)
			{
				if (Disposed)
				{
					return;
				}

				if (disposing)
				{
					if (Writer != null)
					{
						Writer.Dispose();
					}
				}

				Disposed = true;
			}
		}

		private void MessageWriter(string message)
		{
			lock (Locker)
			{
				if (!Disposed && (Writer != null))
				{
					Writer.WriteLine (message);
				}
			}
		}
	}
}
